<?php
namespace App\Http\Controllers\Admin\App;

use App\Services\Admin\ExtService;
use App\Utilities\JiugeForm;
use App\Utilities\Upload;
use Illuminate\Http\Request;

class ExtController extends BaseController
{
    /**
     * 扩展
     */

    protected $view = 'admin.app.ext.';//视图前缀
    protected $url = 'ext';//路由前缀
    protected $model;
    protected $formElementArr = [//表单元素
        //array(表单选项,中文名称,name字段名称,表单提示,js验证规则)
        array(1,'扩展名称','name','扩展名称，2-20字符',1),
        array(2,'扩展图标','icon','图标上传',11),
        array(1,'扩展链接','url','访问链接',11),
    ];
    protected $fieldShowArr = [
        'id' => 'ID',
        'name' => '扩展名称',
        'icon' => '扩展图标',
        'url' => '扩展链接',
        'createTime' => '创建时间',
    ];

    public function __construct()
    {
        parent::__construct();
        $this->prefix_url = $this->prefix_url.'/'.$this->url;
        $this->model = new ExtService();
        view()->share('prefix_url',$this->prefix_url);
        view()->share('jiugeForm',new JiugeForm($this->prefix_url));
    }

    public function index()
    {
        $models = $this->model->getIndex();
        return view($this->view.'index',array(
            'datas' => $models,
        ));
    }

    public function create()
    {
        return view($this->formView.'edit',array(
            'sels' => $this->formElementArr,
            'options' => array(),
        ));
    }

    public function store(Request $request)
    {
        $data = $this->getData($request);
        $this->model->add($data);
        return redirect($this->prefix_url);
    }

    public function edit($id)
    {
        return view($this->formView.'edit',array(
            'sels' => $this->formElementArr,
            'options' => array(),
            'data' => $this->model->getOne($id),
        ));
    }

    public function update(Request $request,$id)
    {
        $model = $this->model->getOne($id);
        $data = $this->getData($request);
        $this->model->modify($data,$id);
        return redirect($this->prefix_url);
    }

    public function getData(Request $request)
    {
        $name = $request->name;
        $url = $request->url;
        if (!$name || !$url) {
            echo "<script>alert('数据不全！');history.go(-1);</script>"; exit;
        }
        $icon = '';
        if (isset($icon)) {
            $icon = Upload::uploadImg($request,'icon');
        }
        return array(
            'name' => $name,
            'url' => $url,
            'icon' => $icon,
        );
    }

    public function getModel($id)
    {
        $model = $this->model->getOne($id);
        if (!$model) {
            echo "<script>alert('记录不存在！');history.go(-1);</script>"; exit;
        }
        return $model;
    }
}
